package com.mango.config;

import android.Manifest;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.webkit.WebSettings;

import com.mango.request.Algorithm;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

public final class NetworkConfig {
    private static Application app() {
        return BaseWall.getInstance().getApplication();
    }

    public static String getIp() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) app().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if ((info.getType() == ConnectivityManager.TYPE_MOBILE) || (info.getType() == ConnectivityManager.TYPE_WIFI)) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    // Do nothing.
                }
            }
        }
        return "";
    }

    private static String getLocalIpV6() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intF = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intF.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public static String getIp6() {
        final String[] hostIp6 = new String[1];
        new Thread(new Runnable() {
            @Override
            public void run() {
                hostIp6[0] = getLocalIpV6();
            }
        }).start();
        //过滤找到真实的ipv6地址
        if (hostIp6[0] != null && hostIp6[0].contains("%")) {
            String[] split = hostIp6[0].split("%");
            String s1 = split[0];
            if (s1 != null && s1.contains(":")) {
                String[] split1 = s1.split(":");
                if (split1.length == 6 || split1.length == 8) {
                    if (split1[0].contains("fe") || split1[0].contains("fc")) {
                        return "0.0.0.0";
                    } else {
                        return s1;
                    }
                }
            }
        }
        return "0.0.0.0";
    }

    public static String getMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!"wlan0".equalsIgnoreCase(nif.getName())) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null || macBytes.length == 0) {
                    continue;
                }
                StringBuilder result = new StringBuilder();
                for (byte b : macBytes) {
                    result.append(String.format("%02X", b)).append(":");
                }
                String mac = result.toString();
                if (mac.length() > 0) {
                    mac = mac.substring(0, result.length() - 1);
                }
                return mac;
            }
        } catch (Exception x) {
            x.printStackTrace();
        }
        return "";
    }

    public static String getMacMd5() {
        return Algorithm.MD5Encrypt(getMac()).toLowerCase(Locale.getDefault());
    }

    public static int getConnectionType() {
        NetworkInfo networkInfo = ((ConnectivityManager) app().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        // 判断网络连通性
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                //WIFI
                return 100;
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                        return 1;
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        return 2;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B:
                    case TelephonyManager.NETWORK_TYPE_EHRPD:
                    case TelephonyManager.NETWORK_TYPE_HSPAP:
                        return 3;
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        return 4;
                    case TelephonyManager.NETWORK_TYPE_NR:
                        return 5;
                    default:
                        if (_strSubTypeName.equalsIgnoreCase("GSM")) {
                            return 2;
                        } else if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                || _strSubTypeName.equalsIgnoreCase("WCDMA")
                                || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            return 3;
                        } else {
                            return 0;
                        }
                }
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public static int getOperatorType() {
        int opeType;
        String mno = getMno();
        // 中国联通
        if ("46001".equals(mno) || "46006".equals(mno) || "46009".equals(mno)) {
            opeType = 3;
            // 中国移动
        } else if ("46000".equals(mno) || "46002".equals(mno) || "46004".equals(mno) || "46007".equals(mno)) {
            opeType = 1;
            // 中国电信
        } else if ("46003".equals(mno) || "46005".equals(mno) || "46011".equals(mno)) {
            opeType = 2;
        } else {
            opeType = 99;
        }
        return opeType;
    }

    public static String getMno() {
        TelephonyManager tm = (TelephonyManager) app().getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSimOperator();
    }

    public static String getBssid() {
        WifiManager wifiManager = (WifiManager) app().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        return info == null ? "" : info.getBSSID();
    }

    public static String getSsid() {
        WifiManager wifiMgr = (WifiManager) app().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiMgr.getConnectionInfo();
        String ssid = info == null ? "" : info.getSSID();
        //Android8.0 要用以下方法，获取ssid
        if ("<unknown ssid>".equalsIgnoreCase(ssid)) {
            ConnectivityManager ctm = (ConnectivityManager) app().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = ctm.getActiveNetworkInfo();
            ssid = networkInfo == null ? "" : networkInfo.getExtraInfo();
        }
        return ssid;
    }

    public static int getInfoLA() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && app().checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            return 0;
        TelephonyManager tel = (TelephonyManager) app().getSystemService(Context.TELEPHONY_SERVICE);
        CellLocation cel = tel.getCellLocation();
        if (cel instanceof CdmaCellLocation) {
            CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cel;
            try {
                return cdmaCellLocation.getNetworkId();
            } catch (Exception e) {
                return 0;
            }
        } else if (cel instanceof GsmCellLocation) {
            GsmCellLocation gsmCellLocation = (GsmCellLocation) cel;
            try {
                return gsmCellLocation.getLac();
            } catch (Exception e) {
                return 0;
            }
        }
        return 0;
    }

    public static int getInfoCI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && app().checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            return 0;
        TelephonyManager tel = (TelephonyManager) app().getSystemService(Context.TELEPHONY_SERVICE);
        CellLocation cel = tel.getCellLocation();
        if (cel instanceof CdmaCellLocation) {
            CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cel;
            try {
                return cdmaCellLocation.getBaseStationId();
            } catch (Exception e) {
                return 0;
            }
        } else if (cel instanceof GsmCellLocation) {
            GsmCellLocation gsmCellLocation = (GsmCellLocation) cel;
            try {
                return gsmCellLocation.getCid();
            } catch (Exception e) {
                return 0;
            }
        }
        return 0;
    }

    public static String getUserAgent() {
        String userAgent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(app());
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = (userAgent == null
                ? 0 : userAgent.length()); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
